/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.aggregate_exception;

import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import junit.framework.AssertionFailedError;

public class AggregateAssertionFailedError extends AssertionFailedError {
	private final List<AssertionFailedError> errors;
	
	public AggregateAssertionFailedError() {
		this(new LinkedList<AssertionFailedError>());
	}

	public AggregateAssertionFailedError(AssertionFailedError assertionFailedError) {
		this();
		add(assertionFailedError);
	}

	public AggregateAssertionFailedError(List<AssertionFailedError> errors) {
		this.errors = errors;
	}

	public void add(AssertionFailedError assertionFailedError) {
		if (assertionFailedError != null) {
			errors.add(assertionFailedError);
		}
	}

	public void throwIfContains() {
		if (errors.size() > 0) {
			throw this;
		}
	}

	@Override
	public void printStackTrace() {
		printStackTrace(System.err);
	}

	@Override
	public void printStackTrace(PrintStream printStream) {
		printStackTrace(new PrintWriter(printStream));
	}

	@Override
	public void printStackTrace(PrintWriter printWriter) {
		if (errors.size() == 1) {
			errors.get(0).printStackTrace(printWriter);
		}
		else {
			printWriter.println("AggregateAssertionFailedError: " + errors.size() + " errors");
	
			int index = 1;
			for (Iterator iterator = errors.iterator(); iterator.hasNext(); index++ ) {
				printWriter.print("Error " + index + ": ");
	
				AssertionFailedError assertionFailedError = (AssertionFailedError) iterator.next();
	
				assertionFailedError.printStackTrace(printWriter);
	
				if (iterator.hasNext()) {
					printWriter.println();
				}
			}
		}

		printWriter.flush();
	}
}
